home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2387 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.gate.net!pslfl2-37
  2. From: bhutto@gate.net (William Hutto)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: ** Array problem **
  5. Date: 20 Jan 1996 23:03:25 GMT
  6. Organization: CyberGate, Inc.
  7. Message-ID: <4drsbt$il4@news.gate.net>
  8. References: <4dqh8k$ov9@neptunus.pi.net>
  9. NNTP-Posting-Host: pslfl2-37.gate.net
  10. X-Newsreader: News Xpress Version 1.0 Beta #4
  11.  
  12. In article <4dqh8k$ov9@neptunus.pi.net>, mv@pi.net spake:
  13. ;
  14. ;Hello Bill Wendlig (and everybody else),
  15. ;
  16. ;
  17. ;A couple a days ago you replied to a message from me about some
  18. ;problems with a piece if code..
  19. ;You handed me some tips and corrections about a double indexed array that
  20. ;turned out to be a 3-dimensional one..
  21. ;
  22. ;I implemented you corrections but to no good, it made things even worse...
  23. ;But than again I'm not a an experienced C-programmer..
  24. ;
  25. ;But could you please tell me why this code works...
  26. ;
  27. ;
  28. ;--------------------------------------------
  29. ;
  30. ;#include <stdio.h>
  31. ;#include <stdlib.h>
  32. ;#include <string.h>
  33. ;#include <malloc.h>
  34. ;
  35. ;
  36. ;char *s;
  37. ;char a[20][20];
  38. ;
  39. ;
  40. ;
  41. ;int main (void)
  42. ;
  43. ;{
  44. ; int i=0;
  45. ;
  46. ;  s=(char *)malloc(18);
  47. ;   strcpy(s,"Blah blah, this works");
  48.  
  49. "Blah blah, this works" needs 22 characters. You've only allocated 18. 
  50.  
  51. 22-18= 4 characters illegally written to memory. If your code runs past this 
  52. point...
  53.  
  54. ;    for (i=0; i<=15; i++)
  55. ;     {
  56. ;      strcpy(a[i],s);
  57.  
  58. sizeof a[i] = 20, so:
  59.  
  60. 22-20 = 2 characters written to a[i+1] which on the last iteration will write 
  61. 2 characters beyond the end of *a* (illegally). 
  62.  
  63.  
  64. ;     }
  65. ;    for (i=0; i<=15; i++)
  66. ;     {
  67. ;      printf("%s\n",a[i]);
  68. ;     }
  69. ;  free(s);
  70. ; return 0;
  71. ;}
  72. ;
  73. ;--------------------------------
  74. ;
  75. ;This is the same situation but it works fine here ?!
  76. ;
  77. In my vernacular, *works* does not correctly describe this code.
  78.  
  79. Bill
  80.  
  81. "Whatcha got on?...Your mind?"
  82.